import axios from "axios"; // 引用axios
import { Toast } from 'vant'

const request = axios.create({
    baseURL: process.env.NODE_ENV === "production" ? process.env.VUE_APP_BASE_API : "/api",
    timeout: 5000,
});

function startLoading() {
    // 开始加载
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
    });
}
function endLoading() {
    // 结束加载
    Toast.clear()
}
// 请求前
request.interceptors.request.use(config => {
    startLoading()
    return config
}, error => {
    Promise.reject(error)
})
// 请求后
request.interceptors.response.use(
    response => {
        endLoading()
        return Promise.resolve(response.data)
    },
    error => {
        startLoading()
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    console.log(401)
                    break;
                case 403:
                    console.log(403)
                    break;
                case 404:
                    Toast({
                        message: '网络请求不存在',
                        duration: 1500,
                        forbidClick: true
                    })
                    console.log(404)
                    break;
                case 500:
                    console.log(500)
                    break;
            }
        }
        return Promise.reject(error.response)
    }
)

export default request;
